package com.qf.driver.mqtt.handler;

import com.qf.common.sdk.bean.MessageHeader;
import com.qf.common.sdk.bean.MessagePayload;
import com.qf.common.sdk.bean.MessageType;
import com.qf.common.sdk.bean.MqttMessage;
import com.qf.common.utils.JsonUtil;
import com.qf.driver.service.MqttReciveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;

/**
 * 接收emqx服务器中的topic主题数据
 * 通过mqtt协议连接
 * @author 千锋健哥
 */
@Slf4j
@Configuration
public class MqttReciverHandler {

   @Autowired
   private MqttReciveService reciveService;

    //监听这个通道中的数据并接收
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler valueHandler() {
        return message -> {
            log.info("设备发送过来的数据是:" + message.getPayload().toString());
            log.info("设备发送过来的json数据是:" + JsonUtil.toJsonString(message.getHeaders()));

            if (message != null) {
                //获取设备发送过来的消息载荷, 也就是内容数据
                MessagePayload messagePayload = new MessagePayload(message.getPayload().toString(), MessageType.MQTT);
                //获取发送过来的消息请求头
                MessageHeader messageHeader = new MessageHeader(message.getHeaders());
                //将消息头和载荷封装成消息对象
                MqttMessage mqttMessage = new MqttMessage(messageHeader, messagePayload);

                //掉用service将数据进行加工处理后发到rabbitmq中
                reciveService.reciveValue(mqttMessage);
            } else {
                log.info("==============设备发送过来的消息数据为空, 不予保存!===============");
            }
        };
    }
}
